<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------

namespace app\user\controller;

use app\model\CustomerFileModel;
use app\model\CustomerModel;
use app\model\OrderModel;
use app\model\OrderOperationModel;
use app\model\OrderSonModel;
use app\model\RecordModel;
use app\model\ReportModel;
use app\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Validate;

/**
 * Class AdminIndexController
 * @package app\user\controller
 *
 * @adminMenuRoot(
 *     'name'   =>'用户管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 10,
 *     'icon'   =>'group',
 *     'remark' =>'用户管理'
 * )
 *
 * @adminMenuRoot(
 *     'name'   =>'用户组',
 *     'action' =>'default1',
 *     'parent' =>'user/AdminIndex/default',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   =>'',
 *     'remark' =>'用户组'
 * )
 */
class AdminIndexController extends AdminBaseController
{
    protected  $admin_name = '';

    public function _initialize()
    {
        $this->admin_name = UserModel::where('id',session('ADMIN_ID'))->value('user_login');
    }

    /**
     * 后台本站用户列表
     * @adminMenu(
     *     'name'   => '本站用户',
     *     'parent' => 'default1',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('user_admin_index_view');
        if (!empty($content)) {
            return $content;
        }
		 $data = $this->request->param();
        $list = CustomerModel::where(function (Query $query) {
                $data = $this->request->param();
                if (!empty($data['phone'])) {
                    $phone = trim($data['phone']);
                    $query->where('phone', 'like',"%$phone%");
                }
                if(!empty($data['name'])){
                    $user_id = Db::name('user')->where('user_login',$data['name'])->value('id');
                    if(!empty($user_id)){
                        $query->where('lawyer_id','=',$user_id)->whereOr('about_id','=',$user_id);
                    }else{
                        $query->where('id','=',null);
                    }
                }
          		
                //地区筛选
                if (!empty($data['province'])) {
                    $province = trim($data['province']);
                    $query->where('province', 'like', "%$province%");
                }
                if (!empty($data['city'])) {
                    $city = trim($data['city']);
                    $query->where('city', 'like', "%$city%");
                }
                if (!empty($data['area'])) {
                    $area = trim($data['area']);
                    $query->where('area', 'like', "%$area%");
                }
           //状态筛选
                if(!empty($data['status'])){
                    $status = $data['status'];
                    $query->where('status','like',"%$status%");
                }

            })
            ->with(['getAbout'=>function($query2){
                $query2->field('id,user_login');
            }])
            ->with(['getLawyer'=>function($query3){
                $query3->field('id,user_login');
            }])
            ->order("create_time DESC")
            ->paginate(10);
      $list->appends($data);
        // 获取分页显示
        $page = $list->render();
        $list = $list->toArray();
        foreach ($list['data'] as $k=>$v){
            //判断用户是否已有订单
            $order_list = OrderModel::where('user_id',$v['id'])->order('create_time desc')->select()->toArray();
            if(!empty($order_list)){
                $list['data'][$k]['order'] = $order_list;
            }else{
                $list['data'][$k]['order'] = '';
            }
            //查询用的的报告
            $report = ReportModel::where('user_id',$v['id'])->select()->toArray();
            if(!empty($report)){
                $list['data'][$k]['report'] = $report;
            }else{
                $list['data'][$k]['report'] = '无';
            }
        }
       if(!empty($data['status'])){
            $status = $data['status'];
        }else{
            $status = '';
        }
        $this->assign('list', $list['data']);
        $this->assign('page', $page);
       	$this->assign('status',$status);
        // 渲染模板输出
        return $this->fetch();
    }


    /**
     * 用户详情
     * user_id   用户id
     */
    public function user_details()
    {
        $user_id = request()->param('user_id');
        $user_details = CustomerModel::where('id',$user_id)->find();
        $user_details['order'] = OrderModel::where('user_id',$user_id)->field('order_no,order_type')->select();
        $user_details['file_number'] = CustomerFileModel::where('user_id',$user_id)->select();
        $record = RecordModel::where('user_id',$user_id)->field('type_name,content')->select();
        return view('',['user_details'=>$user_details,'record'=>$record]);
    }

    /**
     * 修改用户信息
     */
    public function user_edit()
    {
        $post = request()->param();
        $model = new CustomerModel();
        $id = $model->add_update($model,$post);
        if($id){
            return_json(1,'修改成功');
        }else{
            return_json(0,'修改失败');
        }
    }

    /**
     * 用户添加
     */
    public function add_user()
    {

        $validate = new Validate([
            'phone'  => 'require|max:11',
        ]);
        $validate->message([
            'phone.require' => '手机号不能为空',
            'phone.max' => '手机号不能超过11位',
        ]);

        $data = request()->param();
        if (!$validate->check($data)) {
            return_json(0,$validate->getError());
        }
        //判断用户是否已经存在
        $user_info = Db::name('customer')->where('phone',$data['phone'])->find();
        if(!empty($user_info)){
            return_json(0,'该用户已经存在,请勿重复添加!');
        }
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $customer_data['status'] = '待处理';
            $customer_data['phone'] = $data['phone'];
            $customer_data['create_time'] = time();
//            $res = $this->record($record_data,'',$customer_data);
            $user_id = Db::name('customer')->insertGetId($customer_data);
            //添加用户状态记录
            $record_data['user_id'] = $user_id;
            $record_data['type_name'] = '录入时间';
            $record_data['feedback'] = '添加用户';
            $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name.','.$record_data['feedback'];
            $admin_id = session('ADMIN_ID');
            $record_data['admin_id'] = $admin_id;
            $record_data['create_time'] = time();
            $res = Db::name('record')->insert($record_data);

            if($res && $user_id){
                //提交事务
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }
    }


    /**
     * 指派人员以及重新指派
     * user_id    用户id
     * admin_id   操作人员
     * about_name   指派人员id
     */
    public function appointees()
    {
        $validate = new Validate([
            'user_id' => 'require',
            'about_name' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
            'about_name.require'   => '指派人员不能为空',
        ]);
        $data = request()->param();
        if(!$validate->check($data)){
            return_json(0,$validate->getError());
        }

        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            //获取约访人id
            $about_id = Db::name('user')->where('user_login',$data['about_name'])->value('id');
            //用户操纵记录
            $record_data['user_id'] = $data['user_id'];
            $record_data['type_name'] = '指派约访人';
            $record_data['about_id'] = $about_id;
            $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name.','.$data['about_name'];
            //用户状态
            $customer_data['about_id'] = $about_id;
            $customer_data['status'] = '待约访';
            $res = $this->record($record_data,$data['user_id'],$customer_data);
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }
    }


    /**
     * 约访
     * user_id    用户id
     * admin_id   操作人id
     * visit_type 约访类型
     * feedback   反馈
     * time   反馈
     */
    public function appointed()
    {
        $validate = new Validate([
            'user_id' => 'require',
            'visit_type' => 'require',
            'feedback' => 'require',
            'time' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
            'visit_type.require'   => '约访类型不能为空',
            'feedback.require'   => '访问记录不能为空',
            'time.require'   => '约访时间不能为空',
        ]);
        $data = request()->param();
        if(!$validate->check($data)){
            return_json(0,$validate->getError());
        }
        //查询用户访问记录做追加
        $visit_number = RecordModel::where('user_id',$data['user_id'])->where('visit_type','<>','')->order('time desc')->value('visit_number');
        //拼接操作信息
        $record_data['type_name'] = '第'.($visit_number+1).'约访';
        $record_data['visit_number'] = $visit_number+1;
        $record_data['user_id'] = $data['user_id'];
        $record_data['visit_type'] = $data['visit_type'];
        $record_data['feedback'] = $data['feedback'];
        $record_data['about_id'] = session('ADMIN_ID');
        $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name.','.$data['visit_type'].','.$data['feedback'];
        $record_data['time'] = strtotime($data['time']);
        //修改用户状态信息
        $customer_data['status'] = $record_data['type_name'];
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $res = $this->record($record_data,$data['user_id'],$customer_data);
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }
    }


    /**
     * 丢入公海
     * user_id      用户id
     * feedback     反馈
     */
    public function throw_waters()
    {
        $validate = new Validate([
            'user_id' => 'require',
            'feedback' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
            'feedback.require'   => '原因不能为空',
        ]);
        $data = request()->param();
        if(!$validate->check($data)){
            return_json(0,$validate->getError());
        }
        //拼接操作信息
        $record_data['type_name'] = '丢入公海';
        $record_data['user_id'] = $data['user_id'];
        $record_data['feedback'] = $data['feedback'];
        $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name.','.$data['feedback'];

        //修改用户状态信息
        $customer_data['status'] = '公海';
        $customer_data['about_id'] = '';
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $res = $this->record($record_data,$data['user_id'],$customer_data);
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }
    }

    /**
     * 捡起
     * user_id        用户id
     * admin_id       操作人id
     */
    public function pick_up()
    {
        $validate = new Validate([
            'user_id' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
        ]);
        $data = request()->param();
        if(!$validate->check($data)){
            return_json(0,$validate->getError());
        }
        $data = request()->param();
        $record_data['type_name'] = '捡起';
        //将约访人改为捡起的操作人
        //拼接操作信息
        $admin_id = session('ADMIN_ID');
        $record_data['about_id'] = $admin_id;
        $record_data['user_id'] = $data['user_id'];
        $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name;
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            //修改用户状态信息
            $customer_data['status'] = Db::name('record')->where('visit_type','<>','')->order('create_time desc')->value('type_name');
            $customer_data['about_id'] = $admin_id;
            $res = $this->record($record_data,$data['user_id'],$customer_data);
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }


    }

    /**
     * 给用户添加父订单
     * user_id     用户id
     * money       订单金额
     * order_type   订单类型
     * about        约访人id
     */
    public function add_order()
    {
        $order_no = time().rand(1111,9999);   //生成父订单号
        $son_no = time().rand(1111,9999);   //生成子订单号
        $validate = new Validate([
            'user_id'=>'require',
            'money'  => 'require',
            'order_type'  => 'require',
            'about'  => 'require',
        ]);
        $validate->message([
            'money.require' => '订单金额不能为空',
            'order_type.require' => '订单类型不能为空',
            'about.require' => '约访人不能为空',
            'user_id.require' => '用户id不能为空',
        ]);

        $post = request()->param();

        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
       //判断用户姓名和手机号是否为空
        $user_info = Db::name('customer')->where('id',$post['user_id'])->find();
        if(empty($user_info['name']) || empty($user_info['id_card'])){
            return_json(0,'用户手机号或身份证为空时不能添加订单!');
        }
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $order_data['order_no'] = $order_no;
            $admin_id = session('ADMIN_ID');
            $order_data['admin_id'] = $admin_id;
            $order_data['user_id'] = $post['user_id'];
            $order_data['status'] = '首款待支付';
            $order_data['order_type'] = $post['order_type'];
            $order_data['about'] = $post['about'];
            $order_data['create_time'] = time();
            //添加父订单记录
            $res = Db::name('order')->insert($order_data);

            //添加子订单
            $son_data['parent_order'] = $order_no;
            $son_data['son_no'] = $son_no;
            $son_data['admin_id'] = $admin_id;
            $son_data['order_name'] = $post['order_type'].'首付';
            $son_data['order_type'] = 1;   //订单类型 1为首款 |２为尾款
            $son_data['payment'] = $post['money'];
            $son_data['pay_money'] = $post['money'];
            $son_data['status'] = '首款待支付';
            $son_data['create_time'] = time();
            $res2 = Db::name('order_son')->insert($son_data);

            //添加订单完成,新增订单状态记录
            $data2['admin_id'] = $admin_id;
            $data2['order_no'] = $order_no;
            $data2['operation'] = '添加订单';
            $data2['order_status'] = '首款待支付';
            $data2['create_time'] = time();
            $res3 = Db::name('order_operation')->insert($data2);

            if($res && $res2 && $res3){
                //提交事务
                Db::commit();
                return_json(1,'操作成功');
            }else{
                //事务回滚
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            //事务回滚
            Db::rollback();
            return_json(0,'操作失败');
        }

    }


    /**
     * 添加报告
     * user_id      用户id
     * report_no    订单编号(后台生成)
     * basic        基本情况(json)
     * content      律师建议
     * admin_id     添加报告的管理员id(后台生成)
     */
    public function add_report()
    {
        $validate = new Validate([
            'user_id' => 'require',
            'basic' => 'require',
            'content' => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
            'title.require'   => '基本情况不能为空',
            'content.require' => '律师建议不能为空',
        ]);
        $data = request()->param();
        if(!$validate->check($data)){
            return_json(0,$validate->getError());
        }
        $admin_id = session('ADMIN_ID');
        $data['admin_id'] = $admin_id;
        $data['report_no'] = 'FLBG'.date('Ymd').rand(00000,99999);
        $model = ReportModel::create($data);
        if($model->id){
            return_json(1,'添加成功');
        }else{
            return_json(0,'添加失败');
        }
    }


    /**
     * 公共记录方法
     * @param array $data
     *
     */
    public function record($record_data=[],$user_id='',$customer_data=[])
    {

        $admin_id = session('ADMIN_ID');
        $record_data['admin_id'] = $admin_id;
        $record_data['create_time'] = time();
        $customer_data['update_time'] = time();
        //插入操作记录
        $result = Db::name('record')->insert($record_data);
        if(empty($user_id)){
            //新增用户
            $result2 = Db::name('customer')->insert($customer_data);
        }else{
            $result2 = Db::name('customer')->where('id',$user_id)->update($customer_data);
        }
        if($result && $result2){
            return true;
        }else{
            return false;
        }
    }



//    /**
//     * 本站用户拉黑
//     * @adminMenu(
//     *     'name'   => '本站用户拉黑',
//     *     'parent' => 'index',
//     *     'display'=> false,
//     *     'hasView'=> false,
//     *     'order'  => 10000,
//     *     'icon'   => '',
//     *     'remark' => '本站用户拉黑',
//     *     'param'  => ''
//     * )
//     */
//    public function ban()
//    {
//        $id = input('param.id', 0, 'intval');
//        if ($id) {
//            $result = Db::name("user")->where(["id" => $id, "user_type" => 2])->setField('user_status', 0);
//            if ($result) {
//                $this->success("会员拉黑成功！", "adminIndex/index");
//            } else {
//                $this->error('会员拉黑失败,会员不存在,或者是管理员！');
//            }
//        } else {
//            $this->error('数据传入失败！');
//        }
//    }
//
//    /**
//     * 本站用户启用
//     * @adminMenu(
//     *     'name'   => '本站用户启用',
//     *     'parent' => 'index',
//     *     'display'=> false,
//     *     'hasView'=> false,
//     *     'order'  => 10000,
//     *     'icon'   => '',
//     *     'remark' => '本站用户启用',
//     *     'param'  => ''
//     * )
//     */
//    public function cancelBan()
//    {
//        $id = input('param.id', 0, 'intval');
//        if ($id) {
//            Db::name("user")->where(["id" => $id, "user_type" => 2])->setField('user_status', 1);
//            $this->success("会员启用成功！", '');
//        } else {
//            $this->error('数据传入失败！');
//        }
//    }
}
